import { useKeyPress } from 'ahooks'
import React from 'react'
import { useDispatch } from 'react-redux'
import {
  copySelectedComponent,
  pasteCopiedComponent,
  removeSelectedComponent,
  selectedNextComponent,
  selectPrevComponent,
} from '../store/componentsReducer'

import { ActionCreators as UndoActionCreators } from 'redux-undo'

function isACtiveElementValid() {
  const activeElement = document.activeElement
  if (activeElement === document.body) return true
  if (activeElement?.matches('div[role="button"]')) return true
  return false
}

const useBindCanvasKeyPress = () => {
  const dispatch = useDispatch()
  useKeyPress(['backspace', 'delete'], () => {
    if (!isACtiveElementValid()) return
    dispatch(removeSelectedComponent())
  })
  useKeyPress(['ctrl.c', 'meta.c'], () => {
    if (!isACtiveElementValid()) return
    dispatch(copySelectedComponent())
  })

  useKeyPress(['ctrl.v', 'meta.v'], () => {
    if (!isACtiveElementValid()) return
    dispatch(pasteCopiedComponent())
  })

  useKeyPress('uparrow', () => {
    if (!isACtiveElementValid()) return
    dispatch(selectPrevComponent())
  })
  useKeyPress('downarrow', () => {
    if (!isACtiveElementValid()) return
    dispatch(selectedNextComponent())
  })
  useKeyPress(
    ['ctrl.z', 'meta.z'],
    () => {
      dispatch(UndoActionCreators.undo())
    },
    {
      exactMatch: true,
    }
  )
  useKeyPress(
    ['ctrl.shift.z', 'meta.shift.z'],
    () => {
      dispatch(UndoActionCreators.redo())
    },
    {
      exactMatch: true,
    }
  )
}

export default useBindCanvasKeyPress
